package mdm.com.web.controller;

import java.util.List;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import mdm.com.web.common.AjaxResponse;
import mdm.com.web.common.BaseController;
import mdm.com.web.common.Constant;
import mdm.com.web.entity.Permission;
import mdm.com.web.entity.RolePermission;
import mdm.com.web.service.IPermissionService;
import mdm.com.web.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping(value = "permission")
@Api(description = Constant.MODULE_PERMISSION)
// @ApiIgnore
public class PermissionController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(PermissionController.class);

    private final IPermissionService iPermissionService;

    private final IRoleService iRoleService;

    @Autowired
    public PermissionController(IRoleService iRoleService, IPermissionService iPermissionService) {
        this.iPermissionService = iPermissionService;
        this.iRoleService = iRoleService;
    }

    @ApiOperation(value = "新增权限", notes = "请求参数:<br>" + "cPermissionName 权限名称<br>" + "cPermissionType 权限类型")
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public AjaxResponse add(@RequestBody Permission permission) {
        try {
            if (StringUtils.isEmpty(permission.getcPermissionName())
                    || StringUtils.isEmpty(permission.getcPermissionType())) {
                return AjaxResponse.reponseBody(Constant.CHECK_CODE, super.getMessage("permission_check_name_and_type"),
                        null);
            }
            if (iPermissionService.selectByPermissionName(permission.getcPermissionName()) != null
                    || iPermissionService.selectByPermissionType(permission.getcPermissionType()) != null) {
                return AjaxResponse.reponseBody(Constant.CHECK_CODE,
                        super.getMessage("permission_check_name_and_type_exist"), null);
            }
            iPermissionService.add(permission);
            return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, null);
        } catch (Exception e) {
            LOGGER.error("", e);
            return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
        }
    }

    @ApiOperation(value = "删除权限", notes = "请求参数:<br>" + "cPermissionId 权限id")
    @ResponseBody
    @RequestMapping(value = "/remove/{cPermissionId}", method = RequestMethod.DELETE)
    public AjaxResponse remove(@PathVariable Integer cPermissionId) {
        try {
            LOGGER.info("------------param:{}", cPermissionId);
            if (cPermissionId == null) {
                return AjaxResponse.reponseBody(Constant.CHECK_CODE, super.getMessage("permission_check_id"), null);
            }
            iPermissionService.remove(cPermissionId);
            return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, null);
        } catch (Exception e) {
            LOGGER.error("", e);
            return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
        }
    }

    @ApiOperation(value = "修改权限", notes = "请求参数:<br>" + "cPermissionId 权限id<br>" + "cPermissionName 权限名称<br>"
            + "cPermissionType 权限类型")
    @ResponseBody
    @RequestMapping(value = "/modify", method = RequestMethod.PUT)
    public AjaxResponse modify(@RequestBody Permission permission) {
        try {
            LOGGER.info("------------param:{}", permission);
            if (StringUtils.isEmpty(permission.getcPermissionName())
                    || StringUtils.isEmpty(permission.getcPermissionType())) {
                return AjaxResponse.reponseBody(Constant.CHECK_CODE, super.getMessage("permission_check_name_and_type"),
                        null);
            }
            Permission permission1 = iPermissionService.selectByPermissionName(permission.getcPermissionName());
            Permission permission2 = iPermissionService.selectByPermissionType(permission.getcPermissionType());
            if ((permission1 != null && !Objects.equals(permission.getcPermissionId(), permission1.getcPermissionId()))
                    || (permission2 != null
                            && !Objects.equals(permission.getcPermissionId(), permission2.getcPermissionId()))) {
                return AjaxResponse.reponseBody(Constant.CHECK_CODE,
                        super.getMessage("permission_check_name_and_type_exist"), null);
            }
            iPermissionService.modify(permission);
            return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, null);
        } catch (Exception e) {
            LOGGER.error("", e);
            return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
        }
    }

    @ApiOperation(value = "权限查询", notes = "请求参数:<br>" + "pageIndex 页码<br>" + "limit 每页显示条数<br>" + "可选查询条件:<br>"
            + "cPermissionName 权限名称<br>" + "cPermissionType 权限类型<br>" + "startDate 开始时间<br>" + "endDate 结束时间")
    @ResponseBody
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public AjaxResponse page(@RequestBody Permission permission, @RequestParam Integer pageIndex,
            @RequestParam Integer limit) {
        try {
            LOGGER.info("------------param:{}---{}---{}", permission, pageIndex, limit);
            PageHelper.startPage(pageIndex, limit);
            List<Permission> list = iPermissionService.selectByCondition(permission);
            PageInfo result = new PageInfo<>(list);
            return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, result);
        } catch (Exception e) {
            LOGGER.error("", e);
            return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
        }
    }

    @ApiOperation(value = "权限查询", notes = "请求参数:<br>" + "pageIndex 页码<br>" + "limit 每页显示条数<br>" + "可选查询条件:<br>"
            + "cPermissionName 权限名称<br>" + "cPermissionType 权限类型<br>" + "startDate 开始时间<br>" + "endDate 结束时间")
    @ResponseBody
    @RequestMapping(value = "/tree", method = RequestMethod.POST)
    public AjaxResponse tree(@RequestBody Permission permission, @RequestParam Integer pageIndex,
            @RequestParam Integer limit) {
        try {
            LOGGER.info("------------param:{}---{}---{}", permission, pageIndex, limit);
            PageHelper.startPage(pageIndex, limit);
            List<Permission> list = iPermissionService.selectByConditionRole(permission);
            PageInfo result = new PageInfo<>(list);
            return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, result);
        } catch (Exception e) {
            LOGGER.error("", e);
            return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
        }
    }

    @ApiOperation(value = "role 树 初始化", notes = "请求参数:<br>")
    @ResponseBody
    @RequestMapping(value = "/roletree", method = RequestMethod.GET)
    public AjaxResponse roletree(@RequestParam Integer cRoleId) {
        try {
            List<RolePermission> rpl = iRoleService.selectByRoleId(cRoleId);
            Permission permission = new Permission();
            List<Permission> list = iPermissionService.selectByConditionRole(permission);
            for (int i = 0; i < list.size(); i++) {
                for (int j = 0; j < list.get(i).getSubDetail().size(); j++) {
                    for (RolePermission r : rpl) {
                        if (list.get(i).getcPermissionId() == r.getcPermissionId()) {
                            list.get(i).setChecked(Constant.CHECKED_EFFECTIVE);
                        }
                        if (list.get(i).getSubDetail().get(j).getcDetailId() == r.getcDetailId()) {
                            list.get(i).getSubDetail().get(j).setChecked(Constant.CHECKED_EFFECTIVE);
                        }
                    }
                }
            }
            PageInfo result = new PageInfo<>(list);
            return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, result);
        } catch (Exception e) {
            LOGGER.error("", e);
            return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
        }
    }

}
